﻿using CPPEI.BD.Contract;
using CPPEI.BD.RemoteSender;
using CPPEI.Net.UDP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.BD.VMTool.Untils
{
    class VMAgentUtil
    {
        private static UDPClient s_udpClient;

        public static void SendToAgent(string targetIP, int targetPort, Datas.Solution solution)
        {
            string agentIP = System.Configuration.ConfigurationManager.AppSettings["AgentIP"];
            int agentPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AgentPort"]);

            if (s_udpClient == null)
            {
                s_udpClient = new UDPClient(agentPort, new ResponseHandlerFactory());
            }

            for (int index = 0; index < solution.Mapping.Count; index++)
            {
                Datas.Mapping mapping = solution.Mapping[index];

                BD.Contract.ForwardVMPackageData packageData = new ForwardVMPackageData();
                packageData.PackageData = VMUdpUntil.MappingToByte(mapping);
                packageData.TargetIP = targetIP;
                packageData.TargetPort = targetPort;

                byte[] data = Net.Serializer.ToBinary(packageData);

                Net.NetPackage package = new Net.NetPackage(NETCMD.ForwardVMPackage, Net.NetReplayMode.None, 0, data);
                s_udpClient.SendTo(agentIP, package);
                CPPEI.Coolzon.Common.Logger.Debug("发送视频切换数据到agent程序，agent:{0}:{1},device:{2}:{3},length:{4}",
                    agentIP,
                    agentPort,
                    targetIP,
                    targetPort,
                    packageData.PackageData.Length);
            }
        }

        public static void SendToAgent(string targetIP, int targetPort, string strOperate)
        {
            string agentIP = System.Configuration.ConfigurationManager.AppSettings["AgentIP"];
            int agentPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AgentPort"]);
            if (s_udpClient == null)
            {
                s_udpClient = new UDPClient(agentPort, new ResponseHandlerFactory());
            }

           
            byte[] udpData = System.Text.Encoding.Default.GetBytes(strOperate);
            Net.NetPackage package = new Net.NetPackage(NETCMD.ForwardVMPackage, Net.NetReplayMode.None, 0, udpData);
            s_udpClient.SendTo(agentIP, package);
            CPPEI.Coolzon.Common.Logger.Debug("发送操作指令数据到agent程序，agent:{0}:{1},device:{2}:{3},length:{4}",
                agentIP,
                agentPort,
                targetIP,
                targetPort,
                udpData.Length);
        }


    }
}
